// api服务提供
package main

import(
	// "fmt"
	"strings"
	"errors"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"

	"gitee.com/lzqysoft/framework/common/stringfmt"
	"gitee.com/lzqysoft/framework/api/code"
	"gitee.com/lzqysoft/framework/api/request"
	"net/http"
	"encoding/json"
	"github.com/astaxie/beego/plugins/cors"
	"gitee.com/lzqysoft/framework/common/log"
)

func main(){
	log.Info("start server...")
	beego.BConfig.CopyRequestBody = true
	beego.Post("/s1/:module/:service/:action",func(ctx *context.Context){
		ctx.Output.ContentType("application/json; charset=utf-8")
		ctx.Output.SetStatus(200)
		module, service, action, err := getURLParams(ctx.Input.Params())
		res := genRes()
		if err != nil {
			res.setCode(code.ERR_URL)
			ctx.Output.JSON(res, false, false)
		}
			servicePath := []string{service,action}
			stringfmt.StrArrayFristToUpper(servicePath)

			token := ctx.Request.Header.Get("Authorization")
			params := make(map[string]interface{})
			err  = json.Unmarshal(ctx.Input.RequestBody, &params)



			result := request.Request(module,strings.Join(servicePath,"."),token,params)
			//log.Info(result)
			res.setCode(result.Code).setMessage(result.Message).setData(result.Res).setToken(result.Token)
			ctx.Output.JSON(res, false, false)

   })
	beego.ErrorHandler("404", page_not_found)
	beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		AllowCredentials: true,
	}))
	beego.Run()
}



// getURLParams 从url中获取module，service，action
func getURLParams(params map[string]string) (modules, service, action string, err error){

	modules,ok := params[":module"]
	if !ok {
		return "", "", "", errors.New("无效的URL")
	}
	service,ok = params[":service"]
	if !ok {
		return "", "", "", errors.New("无效的URL")
	}
	action,ok = params[":action"]
	if !ok {
		return "", "", "", errors.New("无效的URL")
	}
	err = nil
	return
}

// genRes 自定义返回类型
func genRes() result {
	res := make(map[string]interface{})
	return res
}

// result restful api 返回结果数据定义
type result map[string]interface{}
// setResultData 设置返回数据，并默认返回正确结果
func(r result) setResultData(data interface{}) result{
	r["data"] = data
	r["code"] = 0
	return  r
}
// setError 设置返回错误代码及信息
func(r result) setError(code, message string) result{
	r["code"] = code
	r["message"] = message
	return r
}
// setCode 设置返回状态代码
func(r result) setCode(code string) result{
	r["code"] = code
	return r
}
func(r result) setToken(token string) result{
	r["token"] = token
	return r
}
// setMessage 执行异常时返回的信息
func(r result) setMessage(message string) result{
	r["message"] = message
	return r
}
// setDate 定义返回的数据
func(r result) setData(data interface{}) result{
	r["data"] = data
	return r
}

// page_not_found 自定义404状态
func page_not_found(rw http.ResponseWriter, r *http.Request){
	res := genRes().setCode("404").setMessage("无法匹配此URL")
	v, _:= json.Marshal(&res)
	rw.Write(v)
}

